package com.laolang.thresh.module.auth.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.laolang.thresh.framework.common.util.spring.SpringUtils;
import com.laolang.thresh.framework.redis.util.RedisUtil;
import com.laolang.thresh.framework.web.annotations.AnonymousAccess;
import com.laolang.thresh.module.auth.filter.JwtFilter;
import com.laolang.thresh.module.auth.filter.SecurityAuthenticationFilter;
import com.laolang.thresh.module.auth.handler.LoginFailureHandler;
import com.laolang.thresh.module.auth.handler.LoginSuccessHandler;
import com.laolang.thresh.module.auth.propterties.AuthProperties;
import com.laolang.thresh.module.auth.service.TokenService;
import com.laolang.thresh.module.auth.service.UserDetailsServiceImpl;
import com.laolang.thresh.module.system.user.business.SysUserLoginLogBusiness;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * spring security 配置类.
 *
 * @author laolang
 * @version 0.1
 */
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsServiceImpl userDetailsService;
    private final ObjectMapper objectMapper;
    private final TokenService tokenService;
    private final JwtFilter jwtFilter;
    private final RedisUtil redisUtil;
    private final AuthProperties authProperties;
    private final SysUserLoginLogBusiness sysUserLoginLogBusiness;
    private final AnonymousAccessBean anonymousAccessBean;
    //private final CorsFilter corsFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 禁用 csrf
            .csrf().disable()
            // 跨域支持
            .cors()
            .and()
            // 禁用 session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            //.antMatchers("/auth/login").permitAll()
            // 配置匿名访问
            .antMatchers(
                // 登录
                "/auth/login",
                // tool
                //"/tool/**",
                // druid
                "druid/**",
                // swagger
                "/swagger-ui.html",
                "/doc.html",
                "/webjars/**",
                "/v2/**",
                "/swagger-resources/**"
            ).anonymous()
            .antMatchers(getAnonymousUrls()).anonymous()
            .anyRequest().authenticated()
            .and()
            .addFilterAt(securityAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
            .addFilterAfter(jwtFilter, UsernamePasswordAuthenticationFilter.class)
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    private SecurityAuthenticationFilter securityAuthenticationFilter() throws Exception {
        SecurityAuthenticationFilter filter = new SecurityAuthenticationFilter(objectMapper);
        filter.setAuthenticationManager(authenticationManager());
        filter.setFilterProcessesUrl("/auth/login");
        filter.setAuthenticationSuccessHandler(
            new LoginSuccessHandler(tokenService, redisUtil, authProperties, sysUserLoginLogBusiness));
        filter.setAuthenticationFailureHandler(new LoginFailureHandler());
        return filter;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 获取标有注解 AnonymousAccess 的访问路径.
     */
    private String[] getAnonymousUrls() {
        // 获取所有的 RequestMapping
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = SpringUtils.getBean(RequestMappingHandlerMapping.class)
            .getHandlerMethods();
        Set<String> allAnonymousAccess = new HashSet<>();
        // 循环 RequestMapping
        for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethods.entrySet()) {
            HandlerMethod value = infoEntry.getValue();
            // 获取方法上 AnonymousAccess 类型的注解
            AnonymousAccess methodAnnotation = value.getMethodAnnotation(AnonymousAccess.class);
            // 如果方法上标注了 AnonymousAccess 注解，就获取该方法的访问全路径
            if (methodAnnotation != null) {
                allAnonymousAccess.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
            }
        }
        anonymousAccessBean.setUris(Arrays.asList(allAnonymousAccess.toArray(new String[0])));
        return allAnonymousAccess.toArray(new String[0]);
    }
}
